import { Component } from 'react'
import router from 'umi/router'
import { RouteComponentProps } from 'react-router'
import { Mutation, Query } from 'react-apollo'
import { gql } from 'apollo-boost'
import { Spin } from 'antd'
import OrderForm from './components/form'

interface Props extends RouteComponentProps<{ id: string }> {}

export default class OrderPage extends Component<Props> {
  key = 'Order'
  path = '/orders'

  get id() {
    const { id } = this.props.match.params
    return id.length > 1 ? id : ''
  }

  render = () =>
    ((
      {
        location: {
          query: { edit },
        },
      },
      { id, key, path },
    ) => (
      <Query query={QUERY_ORDER} variables={{ id }} skip={!id}>
        {({ loading, data, refetch }) => (
          <Spin spinning={loading && !!id}>
            <Mutation mutation={UPDATE_OR_CREATE_ORDER}>
              {mutate => (
                <Mutation mutation={DELETE_ORDER}>
                  {deletes => (
                    <OrderForm
                      data={{ ...data[key], id }}
                      editing={!!edit}
                      onCancel={() => router.replace(path + '/' + id)}
                      onEdit={() => router.replace(path + '/' + id + '?edit=1')}
                      onSubmit={async data => {
                        console.log(key, data)
                        const result = await mutate({ variables: data })
                        const { id } =
                          result && result.data['updateOrCreate' + key]
                        if (id === data.id) await refetch()
                        router.replace(path + '/' + id)
                      }}
                    />
                  )}
                </Mutation>
              )}
            </Mutation>
          </Spin>
        )}
      </Query>
    ))(this.props, this)
}

export const QUERY_ORDER = gql`
  query($id: ID!) {
    Order(id: $id) {
      id
      customer {
        id
        name
      }
      items {
        item {
          id
          title
          price
        }
        amount
      }
      state
      createdAt
      updatedAt
    }
  }
`

export const UPDATE_OR_CREATE_ORDER = gql`
  mutation($id: ID!, $state: OrderState!) {
    updateOrCreateOrder(
      create: { state: $state }
      update: { id: $id, state: $state }
    ) {
      id
    }
  }
`

export const DELETE_ORDER = gql`
  mutation($id: ID!) {
    deleteOrder(id: $id) {
      id
    }
  }
`
